package cn.fengwoo.springBoot.aspect;

import com.alibaba.fastjson.JSON;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.NamedThreadLocal;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by fangdaji on 2018/1/10.
 * 2017-01-15 12:31
 */
@Aspect
@Component
public class HttpAspect {

    private final static Logger logger = LoggerFactory.getLogger(HttpAspect.class);

    private final static String url = "";

    // 为了防止线程安全问题,做一个全局变量
    NamedThreadLocal<Long> startTimeLocal = new NamedThreadLocal<>("startTimeLocal");


    @Pointcut("execution(public * cn.fengwoo.springBoot.controller.*.*(..))")
    public void log() {
    }

    @Before("log()")
    public void doBefore(JoinPoint joinPoint) {
        Long startTime = System.currentTimeMillis(); // 记录拦截前的时间毫秒数
        startTimeLocal.set(startTime);

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        //url
        logger.info("【请求地址】:{}", request.getRequestURL());

        //method
        logger.info("【请求方式】:{}", request.getMethod());

        //ip
        logger.info("【请求IP】:{}", request.getRemoteAddr());

        //类方法
        logger.info("【请求类方法】:{}", joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName());

        //参数
        logger.info("【请求参数】:{}", joinPoint.getArgs());
    }

    @After("log()")
    public void doAfter() {
        //logger.info("222222222222");
    }

    @AfterReturning(returning = "object", pointcut = "log()")
    public void doAfterReturning(Object object) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        logger.info("【返回数据】:{}", JSON.toJSONString(object));

        Long stopTime = System.currentTimeMillis(); // 记录结束时间
        String url = request.getRequestURI();
        logger.info("【访问用时】:{}", String.format("%s execute %d ms.", url, stopTime - startTimeLocal.get()));
    }

}
